<?php

namespace app\admin\controller;

use app\admin\validate\AdminDividendValidate;
use app\company\model\CompanyDividend;
use app\service\traits\Crud;
use app\admin\model\AdminDividend as AdminDividendModel;
use app\company\model\Stat;
use app\admin\model\AdminUser;
use app\admin\model\AdminUserDividend;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

class AdminDividend extends Base
{
    private AdminDividendModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new AdminDividendModel();
        $this->validateClass = AdminDividendValidate::class;
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->date = date('Y-m', strtotime($item->date));
        });
    }

    /**
     * 用户分红列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userList(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('list')->check($param);
        $sql   = new AdminUser;
        $sql   = $sql->withSearch('real_name,mobile,identity', $param);
        $sql   = $sql->field('id,real_name,mobile,identity')->where('identity', '<>', 1);
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order($this->orderSort)->select()->each(function ($item) {
            //累计分红金额
            $item->dividend_amount = $item->adminUserDividends()->sum('amount');
        })->append(['identity_text']);
        return $this->success('获取成功', compact('count', 'list'));
    }

    /**
     * 用户分红明细
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userDividendDetail(): Response
    {
        $param = $this->request->param();
        $sql   = new AdminUserDividend;
        $field = 'id,admin_user_id,amount,create_time,company_id,turnover';
        $sql   = $sql->field($field)->withSearch('create_time,admin_user_id', $param);
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order($this->orderSort)->select()->each(function ($item) {
            $item->company_name = '全部公司';
            if ($item->company_id) {
                $item->company_name = \app\admin\model\Company::where('id', $item->company_id)->value('name');
            }
        });
        return $this->success('获取成功', compact('count', 'list'));
    }

    /**
     * 开始分红
     * @return Response
     */
    public function dividend(): Response
    {
        $this->model->startTrans();
        try {
            $param = $this->request->param();
            validate($this->validateClass)->scene('dividend')->check($param);
            //得到当前数据
            $data = $this->model->where('id', $param['id'])->find();
            if ($data->dividend_status == 2) return $this->error('分红已结束');
            $money = $data->money;//总分红金额


            //职能部门人员分红  分红基数金额的10%平分
            $departmentMoney = $money * 0.1;
            $this->department($departmentMoney, $data);
            $money = $money - $departmentMoney;


            //市场招商人员分红
            //得到所有公司的分红金额
            $year    = date('Y', strtotime($data->date));
            $month   = date('m', strtotime($data->date));
            $field   = 'sales_amount,company_id';
            $company = Stat::where('year', $year)->where('month', $month)->type(3)->field($field)->select()->each(function ($item) {
                $company                 = CompanyDividend::gs($item->company_id)->find();

                $item->investor_id       = $company->investor_id;
                $item->investor_ratio    = $company->investor_ratio;//招商人分红比例
                $item->investor_dividend = $company->investor_ratio * $item->sales_amount / 100;//招商人分红基数
                $item->service_id        = $company->service_id;
                $item->service_ratio     = $company->service_ratio;//服务人分红比例
                $item->service_dividend  = $company->service_ratio * $item->sales_amount / 100;//服务人员分红基数
                $item->department_ratio  = $company->department_ratio;//职能部门分红比例
                $item->partner_id        = $company->partner_id;//合伙人
                $item->partner_ratio     = $company->partner_ratio;//合伙人分红比例
                $item->partner_dividend  = $company->partner_ratio * $item->sales_amount / 100;//合伙人分红基数
                $item->total_dividend    = $item->investor_dividend + $item->service_dividend + $item->partner_dividend;//公司分红总基数
            })->toArray();

            //总分红基数
            $total_dividend = array_sum(array_column($company, 'total_dividend'));

            $array = [];
            foreach ($company as $item) {
                if(!\app\admin\model\Company::where('id', $item['company_id'])->value('id') ) continue;//已删除公司不计算在内
                $arr['company_id'] = $item['company_id'];
                $arr['turnover']   = $item['sales_amount'];
                //招商分红记录
                $arr['money']          = $money;
                $arr['admin_user_id']  = $item['investor_id'];
                $arr['dividend_ratio'] = $item['investor_ratio'];
                $arr['amount']         = floor(($item['investor_dividend'] / $total_dividend) * $money * 100) / 100;
                (new AdminUserDividend)->create($arr);
                //服务分红记录
                $arr['admin_user_id']  = $item['service_id'];
                $arr['dividend_ratio'] = $item['service_ratio'];
                $arr['amount']         = floor(($item['service_dividend'] / $total_dividend) * $money * 100) / 100;
                (new AdminUserDividend)->create($arr);
                //合伙人分红记录
                $arr['admin_user_id']  = $item['partner_id'];
                $arr['dividend_ratio'] = $item['partner_ratio'];
                $arr['amount']         = floor(($item['partner_dividend'] / $total_dividend) * $money * 100) / 100;
                (new AdminUserDividend)->create($arr);
            }
            //更新分红状态
            $data->dividend_status = 2;
            $data->save();
            $this->model->commit();
            return $this->success('分红成功');
        } catch (Exception $e) {
            $this->model->rollback();
            return $this->error('分红失败');
        }
    }


    /**
     * 职能部门分红  职能部门没有company_id 已和产品确认
     * @param $allMoney
     * @param $data
     * @return void
     * @throws Exception
     */
    public function department($allMoney, $data)
    {
        $count = AdminUser::where('identity', 2)->status(1)->count();
        // 保留两位小数并向下取整
        $money = floor(($allMoney / $count) * 100) / 100;
        $arr   = AdminUser::where('identity', 2)->field('id')->status(1)->select()->each(function ($item) use ($money, $data) {
            $item->admin_user_id  = $item->id;
            $item->turnover       = $data->turnover;
            $item->cost           = $data->cost;
            $item->dividend_ratio = $data->dividend_ratio;
            $item->money          = $data->money;
            $item->amount         = $money;
            unset($item->id);
        });
        (new AdminUserDividend)->saveAll($arr->toArray());
    }
}